package hh.util.time;

import java.util.Calendar;

/**
 * 日历类不是线程安全的，不仅如此，多线程还会报错
 * @author huanghuai
 * @date 2020/9/30
 */
public class CalenderThreadSafeTest {
    public static void main(String[] args) {
        long count = 10000 * 1;
        m1(count,2012,11);
        m1(count,2013,01);
        m1(count,2000,05);
        new Thread(()->{
            m1(count,2012,11);
        }).start();
        new Thread(()->{
            m1(count,2013,01);
        }).start();

        new Thread(()->{
            m1(count,2000,05);
        }).start();
    }

    private static void m1(long count,int year,int month) {
        for (int i = 0; i < count; i++) {
            String s = yearMonth(year,month);
            if (!s.equals("2012-11")&&!s.equals("2013-1")&&!s.equals("2000-5")) {
                System.out.println(Thread.currentThread() + "--->" + s);
                throw new RuntimeException();
            }
        }
    }
    static Calendar cal = Calendar.getInstance();
    public static String yearMonth(int year,int month) {
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, month-1);
        return cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1);
    }
}
